/*
 * @lc app=leetcode.cn id=219 lang=cpp
 *
 * [219] 存在重复元素 II
 */
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <cmath>
#include <unordered_map>

using namespace std;
// @lc code=start
class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        int n = nums.size();
        unordered_map<int,int> m;
        for(int i = 0;i < n;i++) {
            if(m.count(nums[i])) {
                if (abs(i - m.at(nums[i])) <= k) {
                    return true;
                }else {
                    m[nums[i]] = i;
                }
            }else {
                m.insert(make_pair(nums[i],i));
            }
        }
        return false;
    }
};
// @lc code=end

